﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using System.ComponentModel;
using System.Reflection;
using BrainTechLLC.ThreadSafeObjects;

namespace BrainTechLLC
{
    public partial class ObjectRepository
    {
        public readonly ThreadSafeLookupOnDemand<Type, ObjectStorageForType> ObjectsForType = new ThreadSafeLookupOnDemand<Type, ObjectStorageForType>();

        public void AddObject(Type t, string key, object item)
        {
            var storage = ObjectsForType.Get(t);
            var existing = storage.FindSingle(key);

            if (existing != null)
            {
                throw new Exception(string.Format("Object with key {0} is already in the repository", key));
            }

            storage.Add(key, new ObjectAndKey() { Object = item, Key = key });
        }

        public ObjectAndKey RemoveObject(Type t, string key)
        {
            var storage = ObjectsForType.Get(t);
            var existing = storage.Remove(key, o => o.Key == key);

            if (existing == null)
            {
                throw new Exception(string.Format("Object with key {0} not found in the repository", key));
            }

            return existing;
        }

        public void AddObject<T>(string key, object item)
        {
            AddObject(typeof(T), key, item);            
        }

        public ObjectAndKey RemoveObject<T>(string key)
        {
            return RemoveObject(typeof(T), key);            
        }
    }

    public partial class ObjectAndKey
    {
        public object Object { get; set; }
        public string Key { get; set; }
    }

    public partial class ObjectStorageForType : ThreadSafeListAndLookup<string, ObjectAndKey>
    {
    }
}